<!DOCTYPE html>
<html>
<head>
    <title>毕工的浇花系统</title>
    <style>
        .rectangle {
            width: 90%;
            height: 80px;
            border: 1px solid;
            background-color: #38f87e;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .text {
            font-size: 24px;
        }
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 90%;
            margin: 0 auto;
            border: 1px solid;
            background-color: #a8f5c4;
            margin-top: 10px;
            align-self: flex-start;
        }
        .settinglabel {
            margin-top: 10px;
            width: 70%;
            text-align: right;
        }
        #chart {
            width: 100%; /* 设置宽度为70% */
            height: 150px;
            margin: 0 auto; /* 水平居中对齐 */
        }
    </style>
    <script src="./echarts.min.js"></script>
    <script>
        // 保存数据到缓存
        function saveData() {
            var input = document.getElementById("textInput_ip");
            var text = input.value;
            localStorage.setItem("savedText", text); // 将文本保存到localStorage的"savedText"键中
            // input.value = ""; // 清空文本框内容
        }

        // 从缓存中读取数据
        function loadData() {
            var savedText = localStorage.getItem("savedText"); // 从localStorage中根据键"savedText"读取数据
            if (savedText) {
                var input = document.getElementById("textInput_ip");
                input.value = savedText; // 将读取的缓存内容显示在文本框中
            } else {
                alert("缓存为空");
            }
        }
        // 在页面加载完成时执行读取缓存的动作
        window.onload = function() {
            loadData();
            echar_init();
            setTimeout(fetchData, 2000);
        }

        function get_plant_settings() {
            document.getElementById('input_set').value = 0;
            document.getElementById('input_push_ip').value = 0;
            document.getElementById('input_push_period').value= 0;
            var xhr = new XMLHttpRequest();
            
            var input = document.getElementById("textInput_ip");
            var ip_str = input.value;
            var get_url = "get_plant.php/get?settings=1&&ip="+ip_str
            console.log("get_url=", get_url)
            // xhr.open("GET", "http://192.168.2.185/get?humidity=0", true);
            xhr.open("GET", get_url, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var responseText = xhr.responseText;
                    var jsonObject = JSON.parse(responseText); // 解析 JSON 字符串为 JavaScript 对象
                    // var sssValue = jsonObject.设置; // 获取 "sss" 值
                    console.log("recv=",jsonObject.push_ip);
                    console.log("recv=",jsonObject.set_hmdt);
                    console.log("recv=",jsonObject.push_period);
                    document.getElementById('input_set').value = jsonObject.set_hmdt;
                    document.getElementById('input_push_ip').value = jsonObject.push_ip;
                    document.getElementById('input_push_period').value= jsonObject.push_period;
                   
                }
            };

            xhr.send();
        }
        function get_plant_status() {
            var xhr = new XMLHttpRequest();
            
            var input = document.getElementById("textInput_ip");
            var ip_str = input.value;
            var get_url = "get_plant.php/get?get=1&&ip="+ip_str
            console.log("get_url=", get_url)
            // xhr.open("GET", "http://192.168.2.185/get?humidity=0", true);
            xhr.open("GET", get_url, true);

            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var responseText = xhr.responseText;
                    document.getElementById('label_id_st').innerHTML = responseText;
                    
                    var jsonObject = JSON.parse(responseText); // 解析 JSON 字符串为 JavaScript 对象
                    var sssValue = jsonObject.设置; // 获取 "sss" 值
                    console.log("设置=",sssValue);
                    input_set = document.getElementById('input_set');
                    input_set.value =  sssValue;
                }
            };

            xhr.send();
        }

        function set_act_val() {
            var inputval = document.getElementById("input_set");
            console.log("inputval=", inputval.value)
            if (inputval.value.trim() === "")
            {
                alert("设置不能为空");
            }
            else
            {
                var input_ip = document.getElementById("textInput_ip");
                var ip_str = input_ip.value;
                var set_url = "get_plant.php/get?set=1&&val="+inputval.value+"&&ip="+ip_str
                // console.log("set_url", set_url)
                var xhr = new XMLHttpRequest();
                xhr.open("GET", set_url, true);

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var responseText = xhr.responseText;
                     
                        console.log("设置返回结果=",responseText);
                        // input_set = document.getElementById('input_set');
                        // input_set.value =  sssValue;
                    }
                };
                xhr.send();
            }

        }
        function set_dev_push_ip() {
            var inputval = document.getElementById("input_push_ip");
            console.log("inputval=", inputval.value)
            if (inputval.value.trim() === "")
            {
                alert("设置不能为空");
            }
            else
            {
                var input_ip = document.getElementById("textInput_ip");
                var ip_str = input_ip.value;
                var set_url = "get_plant.php/get?set=1&&srvip="+inputval.value+"&&ip="+ip_str
                // console.log("set_url", set_url)
                var xhr = new XMLHttpRequest();
                xhr.open("GET", set_url, true);

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var responseText = xhr.responseText;
                        console.log("设置返回结果=",responseText);
                        // input_set = document.getElementById('input_set');
                        // input_set.value =  sssValue;
                    }
                };
                xhr.send();
            }

        }
        function set_dev_push_period() {
            var inputval = document.getElementById("input_push_period");
            console.log("inputval=", inputval.value)
            if (inputval.value.trim() === "")
            {
                alert("设置不能为空");
            }
            else
            {
                var input_ip = document.getElementById("textInput_ip");
                var ip_str = input_ip.value;
                var set_url = "get_plant.php/get?set=1&&period="+inputval.value+"&&ip="+ip_str
                // console.log("set_url", set_url)
                var xhr = new XMLHttpRequest();
                xhr.open("GET", set_url, true);

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var responseText = xhr.responseText;
                        console.log("设置返回结果=",responseText);
                        // input_set = document.getElementById('input_set');
                        // input_set.value =  sssValue;
                    }
                };
                xhr.send();
            }

        }
    </script>
    
    <script type="text/javascript">
    function echar_init()
    {
        var chartDom = document.getElementById('his_chart');
        var myChart = echarts.init(chartDom);
        
        var  xdt = ['14', '15','16','17','18']
        var  ydt = ['140', '150','16','220','21']
        var  motordt = ['0', '1','0','1','0']
        option = show_data_format(xdt, ydt, motordt);
        option && myChart.setOption(option);
    }  
    
    // 获取并显示网址内容的函数
    function fetchData() {
        // var label = document.querySelector("label");
        var inputval = document.getElementById("input_nums");
        var url = 'plant_sql.php/ins=0?get_ext=hist&&pagesize='+inputval.value.toString()+'&&pagenum=0';
        console.log(url);
        var chartDom = document.getElementById('his_chart');
        var myChart = echarts.init(chartDom);
        fetch(url)
            .then(response => response.text())
            .then(data => {
                // console.log(data)
                var jsonObject = JSON.parse(data);
                
                // var motor_data = Array(jsonObject.his_tm.length);
                
                options_new = show_data_format(jsonObject.his_tm, jsonObject.his_hum, jsonObject.motor);
                // 更新图表数据
                myChart.setOption(options_new);
            })
            .catch(error => console.log(error));
    }
    var his_data_offset = 0
    function refreshBtn_back_cb() {
        var inputval = document.getElementById("offset_unit");
        his_data_offset += parseInt(inputval.value)
        var inputval = document.getElementById("input_nums");
        var url = 'plant_sql.php/ins=0?get_ext=hist&&pagesize='+inputval.value.toString()+'&&pagenum='+his_data_offset.toString();
        console.log(url);
        
        var chartDom = document.getElementById('his_chart');
        var myChart = echarts.init(chartDom);
        // var  xdt1 = ['24', '25','26','27','28','29','30','31']
        // var  ydt1 = ['240', '250','26','120','221','321','221','121']
        // var  motordt1 = ['0', '0','0','1','0','0','1','0']
        // options_new = show_data_format(xdt1, ydt1, motordt1);
        
        fetch(url)
            .then(response => response.text())
            .then(data => {
                // console.log(data)
                var jsonObject = JSON.parse(data);
                var motor_data = Array(jsonObject.his_tm.length);
                options_new = show_data_format(jsonObject.his_tm, jsonObject.his_hum, jsonObject.motor);
                // 更新图表数据
                myChart.setOption(options_new);
            })
            .catch(error => console.log(error));
    }
    function refreshBtn_foward_cb() {
        var inputval = document.getElementById("offset_unit");
        if(his_data_offset-parseInt(inputval.value) >= 0)
        {   
            his_data_offset -= parseInt(inputval.value);
        }
        else
        {
            alert("没有最新数据了！");
        }
        var inputval = document.getElementById("input_nums");
        var url = 'plant_sql.php/ins=0?get_ext=hist&&pagesize='+inputval.value.toString()+'&&pagenum='+his_data_offset.toString();
        console.log(url);
        var chartDom = document.getElementById('his_chart');
        var myChart = echarts.init(chartDom);
        fetch(url)
            .then(response => response.text())
            .then(data => {
                // console.log(data)
                var jsonObject = JSON.parse(data);
                // var motor_data = Array(jsonObject.his_tm.length);
                options_new = show_data_format(jsonObject.his_tm, jsonObject.his_hum, jsonObject.motor);
                // 更新图表数据
                myChart.setOption(options_new);
            })
            .catch(error => console.log(error));
    }



    
    function show_data_format( xData_his, yData, motor_data){
        xData_his.reverse()
        yData.reverse()
        motor_data.reverse()
        var xData = Array(xData_his.length);
        for (var i = 0; i < xData_his.length; i++) {

            // 将秒时间戳转换为日期对象
            var date = new Date(xData_his[i] * 1000);
            // var year = date.getFullYear();
            // var month = date.getMonth() + 1;
            // var day = date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
            xData[i] = hours.toString()+":"+minutes.toString();
            // console.log(xData_his[i] );
        }
        // 创建配置对象
        var option;
        // mark_size = 0;
        var dynamic_mark_Data= [];
        for (var i = 0; i < motor_data.length; i++) {
            if(motor_data[i] == 1 ){
            
            let newData = {
                    coord: [xData[i], yData[i]],
                    symbol:"pin",
                    
                };    
                dynamic_mark_Data.push(newData);
                console.log(i)
            }
        }
        
        option = {
        title: {
            text: '湿度数据记录曲线'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {},
        toolbox: {
            show: true,
            feature: {
            dataZoom: {
                yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            data: xData
        },
        yAxis: {
            type: 'value',
            axisLabel: {
            // formatter: '{value} %' 
            }
        },
        series: [
            {
            name: '水滴=浇水',
            type: 'line',
            // data: [10, 11, 13, 11, 12, 12, 9],
            data: yData,
            markPoint: { // markLine 也是同理
            data:dynamic_mark_Data,
            },
            }
        ]
        };
        return  option;
    }

  </script>
    <style>
        .my-button {
            width: 100px;
            height: 60px;
            margin-left: 10px;
        }
        .table1 {
        width: 100%;
        border-collapse: collapse;
        }
        
        .table1 th, .table1 td {
        border: 1px solid black;
        padding: 8px;
        }
        
        .table1 th:first-child, .table1 td:first-child {
        width: 80%;
        }
        
        .table1 th:last-child, .table1 td:last-child {
        width: 20%;
        }
    </style>
</head>
<body>
    <div class="rectangle">
        <span class="text">土壤湿度历史曲线</span>
    </div>



    
    <div class="container">
        <div id="his_chart" style="height:400px;width: 100%;margin: 0 auto;">
        </div>
    
    </div>
    
    <div class="container">
        <div  style="width: 70%;height: 300; border: #191a19;margin: 0 auto; margin-bottom: 20px;">
                
            <table class="table1">
                <tr>
                  <th>
                    单页数据:
                    <input type="text" id="input_nums"  placeholder="10" value="50">
                </th>
                  <th>
                    <button id="refreshBtn"  class="my-button" onclick="fetchData()">最新</button>
                  </th>
                </tr>
                <tr>
                    <th>
                        步长:
                        <input type="text" id="offset_unit" width="50px" value="10">
                    </th>
                    <th>
                        <button id="refreshBtn_back" class="my-button" onclick="refreshBtn_back_cb()">向后</button>
                        <button id="refreshBtn_foward" class="my-button" onclick="refreshBtn_foward_cb()">向前</button>
                    </th>
                </tr>
            </table>

    </div>
        </div>
    <div class="container">
        <div class="settinglabel">
            <table class="table1">
                <tr>
                    <th>
                        访问设备IP地址:
                        <input type="text" id="textInput_ip" width="150px" placeholder="192.168.2.185">
                    </th>
                    <th>
                        <button class="my-button" onclick="saveData()">保存</button>
                        <button class="my-button" onclick="loadData()">读取</button>
                    </th>
                </tr>
                <tr>
                    <th>
                        <label id="label_id_st">当前无任何状态,手动刷新</label>
                    </th>
                    <th>
                        <button class="my-button" onclick="get_plant_status()">状态刷新</button>
                    </th>
                </tr>
                <tr>
                    <th>
                        浇水阈值100-700(越大越干燥):
                        <input type="text" id="input_set" width="150px" placeholder="400">
    
                    </th>
                    <th>
                        <button class="my-button" onclick="set_act_val()">设置</button>
                    </th>
                </tr>
                <tr>
                    <th>
                        设备上报IP:
                        <input type="text" id="input_push_ip" width="150px" placeholder="192.168.2.126">
                    </th>
                    <th>
                        <button class="my-button" onclick="set_dev_push_ip()">设置</button>
                    </th>
                </tr>
                <tr>
                    <th>
                        设备上报周期(最小60s):
                        <input type="text" id="input_push_period" width="150px" placeholder="60">
                    </th>
                    <th>
                        <button class="my-button" onclick="set_dev_push_period()">设置</button>
                    </th>
                </tr>
                <tr>
                    <th>
    
                    </th>
                    <th>
                        <button class="my-button" onclick="get_plant_settings()">获取参数</button>
                    </th>
                </tr>
            </table>
        </div>
    </div>
</body>
</html>